package a07_二叉树;

/**
 * <p>
 * a31_修剪二叉搜索树
 * </p>
 *
 * @author flyduck
 * @since 2024/12/26
 */
public class a31_修剪二叉搜索树 {

    public static void main(String[] args) {
        TreeNode treeNode = new TreeNode(1,
                new TreeNode(0),
                new TreeNode(2));
        a31_修剪二叉搜索树 test = new a31_修剪二叉搜索树();
        TreeNode treeNode1 = test.trimBST(treeNode, 1, 2);
        System.out.println(treeNode1);
    }

    public TreeNode trimBST(TreeNode currentNode, int low, int high) {
        if (currentNode == null) {
            return null;
        }

        if(currentNode.val < low){//当前节点比下界限小，这个肯定要删除，那么直接遍历他的右节点
            return trimBST(currentNode.right,low,high);
        }else if(currentNode.val > high){//当前节点比上界限大，这个肯定要删除，那么直接遍历他的左节点
            return trimBST(currentNode.left,low,high);
        }else {//这个节点不删除
            currentNode.left = trimBST(currentNode.left,low,high);
            currentNode.right = trimBST(currentNode.right,low,high);
            return currentNode;
        }
    }
}
